package com.dingwei.superiordiary.PayUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.lihao.baselibrary.utils.L;

import java.util.Map;

/**
 * Created time 2018/4/8.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */
public class AliPayUtls {

    private static AliPayUtls instance = null;

    public static AliPayUtls getInstance() {
        if (instance == null) {
            instance = new AliPayUtls();
        }
        return instance;
    }

    public void setAliPay(final Activity activity, final String aliStr, PayInterface onPayInterFace) {
        this.onPayInterFace = onPayInterFace;
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(aliStr, true);

                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 支付宝支付回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            L.e( "支付宝返回的信息---->" + resultInfo + "" + payResult.getResultStatus() + "---" + payResult.getMemo());
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                L.e( "支付成功");
                if (onPayInterFace != null) {
                    onPayInterFace.paySuccess();
                }
            }else if(TextUtils.equals(resultStatus, "6001")){
                L.e( "支付取消");
                if (onPayInterFace != null) {
                    onPayInterFace.payCancel();
                }
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                L.e( "支付失败");
                if (onPayInterFace != null) {
                    onPayInterFace.payError();
                }
            }
        }
    };


    private PayInterface onPayInterFace;

}
